using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

using NCS.Library;
using NCS.Library.Components.Portal;
using NCS.Library.Components.Security;
using NCS.Library.Utilities;
using NCS.Library.Components.Lang;

namespace NCS.Portal.Administrator.Portals
{
    public partial class PortalManagement : AuthenticatedControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!CurrentUser.IsSuperAdmin && !CurrentUser.IsAdmin) Response.Redirect(AppEnv.ADMIN_CMD);

            if (!IsPostBack)
            {
                DataTable dtPortalByLang = null;

                dgrNameFollowLang.DataSource = builddata(dtPortalByLang);
                dgrNameFollowLang.DataBind();

            }
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            dropPortal.Items.Clear();
            PortalController.LoadPortals(dropPortal.Items);

            if (!CurrentUser.IsSuperAdmin && !CurrentUser.IsAdmin)
            {
                dropPortal.Enabled = false;
            }
            dropPortal.Items.Insert(0, new ListItem("Root", "0"));
            dropPortal.SelectedValue = "0";
            
            DataTable dtPortals = PortalController.GetPortalsByLang(AppEnv.GetLanguage());
            
             DataTable dtRebuildData = new DataTable();

            dtRebuildData.Columns.Add("PortalID", typeof(String));
            dtRebuildData.Columns.Add("Portal_Name", typeof(String));
            dtRebuildData.Columns.Add("Portal_Description", typeof(String));
            dtRebuildData.Columns.Add("Portal_ParentId", typeof(String));
            dtRebuildData.Columns.Add("Level", typeof(String));
            
            dgrPortals.DataSource = PortalController.GetPortalByParentID(dtPortals,dtRebuildData);
            dgrPortals.DataBind();
        }
        public DataTable builddata(DataTable dt)
        {
            DataTable dtRebuildData = new DataTable();

            dtRebuildData.Columns.Add("PortalID", typeof(String));
            dtRebuildData.Columns.Add("Lang", typeof(String));
            dtRebuildData.Columns.Add("Language_Name", typeof(String));
            dtRebuildData.Columns.Add("Portal_Name", typeof(String));
            dtRebuildData.Columns.Add("Portal_Description", typeof(String));
            dtRebuildData.Columns.Add("Portal_ParentId", typeof(String));
            
            try
            {

                DataTable dtLang = MainLanguagesController.GetAll();
                int intdtRowsCount = dtLang.Rows.Count;
                for (int i = 0; i < intdtRowsCount; i++)
                {
                    DataRow dr = dtRebuildData.NewRow();

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (i <= dt.Rows.Count)
                        {
                            dr["PortalID"] = txtPortalID.Text;
                            dr["Lang"] = dtLang.Rows[i]["Language_Culture"];
                            dr["Language_Name"] = dtLang.Rows[i]["Language_Name"];
                            dr["Portal_Name"] = dt.Rows[i]["Portal_Name"];
                            dr["Portal_Description"] = dt.Rows[i]["Portal_Description"];
                            dr["Portal_ParentId"] = dt.Rows[i]["Portal_ParentId"];
                        }
                        else
                        {
                            dr["PortalID"] = txtPortalID.Text;
                            dr["Lang"] = dtLang.Rows[i]["Language_Culture"];
                            dr["Language_Name"] = dtLang.Rows[i]["Language_Name"];
                            dr["Portal_ParentId"] = dt.Rows[i]["Portal_ParentId"];
                            dr["Portal_Name"] = "";
                            dr["Portal_Description"] = "";
                        }
                    }
                    else
                    {
                        dr["PortalID"] = 0;
                        dr["Lang"] = dtLang.Rows[i]["Language_Culture"];
                        dr["Language_Name"] = dtLang.Rows[i]["Language_Name"];
                        dr["Portal_ParentId"] = 0;
                        dr["Portal_Name"] = "";
                        dr["Portal_Description"] = "";
                    }
                    dtRebuildData.Rows.Add(dr);
                }
                return dtRebuildData;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
        protected void dgrPortals_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int portalId;
            switch (e.CommandName)
            {
                case "editportal":
                    portalId = ConvertUtility.ToInt32(e.CommandArgument);
                    Portal_PortalsInfo portal = PortalController.GetPortalsInfoByLang(portalId);
                    txtPortalID.Text = portalId.ToString();
                    chkEnable.Checked = portal.Enable;
                    chkVisible.Checked = portal.Visible;
                    FilePicker1.Text = portal.ImageUrl;
                    dropPortal.SelectedValue = portal.Portal_ParentId.ToString();
                    drl_position.SelectedValue = portal.Position.ToString();

                    DataTable dtPortalByLang = PortalController.GetPortalsById(portalId);
                    dgrNameFollowLang.DataSource = builddata(dtPortalByLang);
                    dgrNameFollowLang.DataBind();                    

                    break;
                case "deleteportal":
                    try
                    {
                        portalId = ConvertUtility.ToInt32(e.CommandArgument);
                        PortalController.DeletePortal(portalId);
                        this.lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;

                        this.AddLog("Portal", " try remove portal id " + e.CommandArgument + " success");
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                        this.AddLog("Portal", " try remove portal id " + e.CommandArgument + " error: " + ex.Message);
                    }
                    break;               
                default:
                    break;
            }
        }
        protected void dgrPortals_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                NCS.WebControls.ButtonRoleDelete btnDeleteRole = (NCS.WebControls.ButtonRoleDelete)e.Row.FindControl("btnDeletePortal");
                btnDeleteRole.OnClientClick = MiscUtility.MSG_DELETE_CONFIRM;
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                int i = 0;
                foreach (DataGridItem item in dgrNameFollowLang.Items)
                {
                    Portal_PortalsInfo _portalInfo = new Portal_PortalsInfo();

                    _portalInfo.PortalID = ConvertUtility.ToInt32(txtPortalID.Text);

                    TextBox txtPortalName = (TextBox)item.FindControl("txtPortalName");
                    _portalInfo.Portal_Name = txtPortalName.Text;

                    TextBox txtPortalDescription = (TextBox)item.FindControl("txtPortalDescription");
                    _portalInfo.Portal_Description = (txtPortalDescription.Text == "") ? txtPortalName.Text : txtPortalDescription.Text;

                    _portalInfo.Lang = item.Cells[1].Text;
                    _portalInfo.PortalID = ConvertUtility.ToInt32(txtPortalID.Text);

                    _portalInfo.Visible = chkVisible.Checked;
                    _portalInfo.Enable = chkEnable.Enabled;
                    _portalInfo.ImageUrl = FilePicker1.Text;
                    _portalInfo.Portal_ParentId = ConvertUtility.ToInt32(dropPortal.SelectedValue);
                    _portalInfo.Position = ConvertUtility.ToInt32(drl_position.SelectedValue);

                    PortalController.UpdatePortal(_portalInfo);
                    i++;
                }

                this.lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;

                this.AddLog("Portal", " try update portal id" + this.txtPortalID + " success");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                this.AddLog("Portal", " try update portal id" + this.txtPortalID + " error: " + ex.Message);
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                Portal_PortalsInfo portalInfo = new Portal_PortalsInfo();

                portalInfo.Visible = chkVisible.Checked;
                portalInfo.Enable = chkEnable.Checked;
                portalInfo.ImageUrl = FilePicker1.Text;
                portalInfo.Portal_ParentId = ConvertUtility.ToInt32(dropPortal.SelectedValue);
                portalInfo.Position = ConvertUtility.ToInt32(drl_position.SelectedValue);
                            
                int portalId = PortalController.AddPortal(portalInfo);
                int i = 0;

                foreach (DataGridItem item in dgrNameFollowLang.Items)
                {
                    Portal_PortalsInfo _portalInfo = new Portal_PortalsInfo();

                    TextBox txtPortalName = (TextBox)item.FindControl("txtPortalName");
                    _portalInfo.Portal_Name = txtPortalName.Text;

                    TextBox txtPortalDescription = (TextBox)item.FindControl("txtPortalDescription");
                    _portalInfo.Portal_Description = txtPortalDescription.Text;
                    _portalInfo.Lang = item.Cells[1].Text;
                    _portalInfo.PortalID = portalId;
                           PortalController.AddPortalFollowLang(_portalInfo);
                    i++;
                }
                /*ad by nguyenhx
                tao mot thu muc va copy file trong thu muc Default vao
                sau do tao ra thu muc css cho thu muc cung bang cach tao ra mot thu muc moi 
                va copy file defaul.css vao 
                 */
                //create portal 
                //CopyFolder(Server.MapPath("/Layouts/"),Server.MapPath("/Layouts/Default/"),Server.MapPath("/Layouts/"+  +"/"));
                //create style
                //CopyFolder(Server.MapPath("/Style/"), Server.MapPath("/Style/Default/"), Server.MapPath("/Style/" + portalInfo.Portal_Name + "/"));
              
                this.lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                this.AddLog("Portal", " try add portal id" + portalId + " success");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                this.AddLog("Portal", " try add portal error: " + ex.Message);
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                int portalId = ConvertUtility.ToInt32(txtPortalID.Text);
                PortalController.DeletePortal(portalId);
                this.lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                this.AddLog("Portal", " try delete portal id" + portalId + " success");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                this.AddLog("Portal", " try delete portal id" + txtPortalID.Text + " error: " + ex.Message);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            dgrNameFollowLang.DataSource = null;
            dgrNameFollowLang.DataBind();
        }


        private void CopyFolder(string path, string strSourceFolderPath, string strDestinationFolderPath)
        {
            try
            {
                if (Directory.Exists(strSourceFolderPath))
                {
                    if (!Directory.Exists(strDestinationFolderPath))
                    {
                        Directory.CreateDirectory(path + "\\" + strDestinationFolderPath);
                    }
                    foreach (string strFilePath in Directory.GetFiles(strSourceFolderPath))
                    {
                        string fath = Path.GetFileName(strFilePath);
                        File.Copy(fath, Path.Combine(strDestinationFolderPath, fath), true);
                    }
                }
                

            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
            }

        }
    }
}